using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Modules.NBrightEspace.Components;
using DotNetNuke.Services.Exceptions;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

namespace DotNetNuke.Modules.NBrightEspace
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditNBrightEspace class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Project : EspaceModuleBase
    {

        #region Event Handlers

        private const string EntityTypeCode = "PROJECT";

        override protected void OnInit(EventArgs e)
        {
            //Set base EntityTypeCode, MUST be done for all NBright child ctrls before OnInit
            base.EntityTypeCode = EntityTypeCode;

            base.OnInit(e);

            //initalize the repeater template based on what we want to see, a list or editing details.
            if (base.ItemId == "")
            {// itemid is blank so display the list
                rpData.Visible = false;

                //All list display functions are processed via the parent class, we just initiallize here.
                base.OnInitActivateList(true, true, MapPath(ControlPath));

            }
            else
            {// itemid is not blank, so display the detail template.
                base.OnInitDetail(rpData);
            }

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack == false)
            {
                PageLoad();
            }
        }

        private void PageLoad()
        {
            try
            {

                if (UInfo.SelType == "client")
                {// return to control from selection page.
                    base.UpdateSelected("client");
                }

                if (base.ItemId == "")
                {
                    //set default filter
                    if (String.IsNullOrEmpty(UInfo.SearchClearAfter))
                    {
                        UInfo.SearchFilters = " and ([XMLData].value('(genxml/checkbox/chkclosed)[1]','nvarchar(5)') = 'False' or isnull([XMLData].value('(genxml/checkbox/chkclosed)[1]','nvarchar(5)'),'') = '') ";
                        UInfo.SearchOrderby = " Order by [xmlData].value('(genxml/textbox/dtereminder)[1]', 'nvarchar(50)') ";
                        UInfo.Save();
                    }

                    // display list   
                    base.BindListData();
                }
                else
                {// display the detail
                    base.DoDetail(rpData);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        #endregion

        #region  "Events "

        protected void CtrlItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "new":
                    Response.Redirect(EditUrl("itemid", "0", EntityTypeCode), true);
                    break;
                case "updateexit":
                    UpdateData();
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "update":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "addlog":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "cancel":
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "delete":
                    base.DeleteData(rpData);
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "selectclient":
                    UpdateData();
                    UInfo.SelType = "client";
                    UInfo.RtnSelUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.RtnUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.Save();
                    Response.Redirect(EditUrl("ClientSel"));
                    break;
                case "goclient":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", GenXmlFunctions.GetHiddenField(rpData, "ClientID"), "client"), true);
                    break;
                case "createactions":
                    UpdateData();
                    CreateActions(Convert.ToInt32(base.ItemId));
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
            }

        }


        #endregion

        #region "presistance methods"


        private void UpdateData()
        {
                if (Page.IsValid)
                {
                    // Does standard update of template form
                    var objInfo = (NBrightInfo)base.UpdateDetailNoValidate(rpData, EntityTypeCode,"");

                    // update project total time
                    EspaceFunctions.UpdateProjectTotalTime(objInfo.ItemID);

                    // Do any special updates that are required.
                    if (string.IsNullOrEmpty(GenXmlFunctions.GetField(rpData, "ProjectRef")))
                    {
                        //if ProjectRef doesn't exist create it
                        var objCtrl = new EspaceController();
                        GenXmlFunctions.SetField(rpData, "ProjectRef", "PR3" + objInfo.ItemID.ToString("000000") + Convert.ToString(DateTime.Now.Year).Substring(2, 2));
                        objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);
                        objCtrl.Update(objInfo);
                    }
                }
        }

        private void CreateActions(int itemId)
        {
            var objInfo = ObjCtrl.Get(itemId);
            if (objInfo != null)
            {

                //Get Action data
                var objAInfo = ObjEspaceCtrl.GetByType(PortalId, ModuleId, "ACTIONS" + itemId.ToString(""));
                if (objAInfo == null)
                {
                    objAInfo = new NBrightInfo();
                    objAInfo.ItemID = -1;
                    objAInfo.TypeCode = "ACTIONS" + itemId.ToString("");
                    objAInfo.XMLData = "<actions></actions>";
                }

                //Get selected actions from project data
                var nodActionList = objInfo.XMLDoc.SelectNodes("genxml/checkboxlist/chkactiontypes/chk");
                if (nodActionList != null)
                {
                    const string strOrderBy = " order by [xmlData].value('(genxml/hidden/actionname)[1]', 'nvarchar(50)')";

                    foreach (XmlNode nodAction in nodActionList)
                    {
                        var singleNode = nodAction.SelectSingleNode("./@value");
                        if (singleNode != null && singleNode.InnerText.ToLower() == "true")
                        {
                            var selectSingleNode = nodAction.SelectSingleNode("./@data");
                            if (selectSingleNode != null)
                            {
                                var actionTypeNum = selectSingleNode.InnerText;
                                var strFilter = " and [xmlData].value('(genxml/hidden/actiontypes)[1]', 'nvarchar(50)') like '%;" + actionTypeNum + ";%' ";
                                var l = ObjCtrl.GetList(-1, -1, "ACTIONS", strFilter, strOrderBy);
                                foreach(NBrightInfo obj in l)
                                {
                                    if (String.IsNullOrEmpty(objAInfo.GetXmlNode("actions/action[id='" + obj.ItemID.ToString("") + "']")))
                                    {
                                        var strXml = "<actions><action><id>" + obj.ItemID.ToString("") + "</id><name>" + obj.GetXmlProperty("genxml/textbox/txtactionname") + "</name><category>" + obj.GetXmlProperty("genxml/dropdownlist/ddlcategory") + "</category><summary><![CDATA[" + obj.GetXmlProperty("genxml/textbox/txtsummary") + "]]></summary><done>False</done></action></actions>";
                                        objAInfo.AddXmlNode(strXml, "actions/action", "actions");
                                    }
                                }
                            }
                        }
                    }
                    base.UpdateData(objAInfo);
                }
            
            }
        }


        #endregion

    }

}